package com.cuiweiyou.gdx_1_9_10.stage;

import android.util.Log;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.Box2D;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.EdgeShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.cuiweiyou.gdx_1_9_10.actor.DemoActor2;
import com.cuiweiyou.gdx_1_9_10.event.Actor2ClickListener;

public class Stage2 extends BaseStage {
    private DemoActor2 actor;
    private SpriteBatch batch;
    Box2DDebugRenderer debugRenderer;
    World world;
    Body ground;
    public Stage2() {
        Box2D.init();
        batch = new SpriteBatch();
        world = new World(new Vector2(0.0f, -9.8f), true);
        actor = new DemoActor2("cat/1.png", world,batch);
        //actor.setPosition(200, 1200);
        addActor(actor);

        createGround();

        actor.addListener(new Actor2ClickListener());
        debugRenderer = new Box2DDebugRenderer();
    }

    private void createGround() {
        if (ground != null) world.destroyBody(ground);

        BodyDef bodyDef = new BodyDef();
        bodyDef.type = BodyDef.BodyType.KinematicBody;

        FixtureDef fixtureDef = new FixtureDef();

        EdgeShape shape = new EdgeShape();
        shape.set(-getWidth()/2,0,getWidth(),-getHeight()/2);
        fixtureDef.shape = shape;
        ground = world.createBody(bodyDef);
        ground.createFixture(fixtureDef);

        shape.dispose();
    }

    @Override
    public void render() {
        stepWorld();

        Gdx.gl.glClearColor(0, 0, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        actor.render();
        Log.d("body", actor.getBody().getPosition().y + "---" + actor.getY());
        super.render();
        Matrix4 matrix4 = new Matrix4();
        debugRenderer.render(world, matrix4);
    }

    static final float STEP_TIME = 1f/60f;
    float accumulator = 0;

    private void stepWorld() {
        float delta = Gdx.graphics.getDeltaTime();

        accumulator += Math.min(delta, 0.25f);

        if (accumulator >= STEP_TIME) {
            accumulator -= STEP_TIME;

            world.step(STEP_TIME, 6, 2);
        }
    }

    @Override
    public void dispose() {
        actor.clear();
        debugRenderer.dispose();
        super.dispose();
    }
}
